package com.gis.postgis.geojson.parsers;

import java.io.IOException;
import java.lang.annotation.Annotation;

import com.fasterxml.jackson.core.JsonParser;
import com.fasterxml.jackson.databind.JavaType;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.fasterxml.jackson.databind.node.ArrayNode;
import com.fasterxml.jackson.databind.node.ObjectNode;
import com.gis.postgis.geojson.annotation.GeoJsonGeometries;
import com.gis.postgis.geojson.deserializer.GeoJsonDeserializer;
import com.gis.postgis.geojson.document.DocumentFactoryException;
import com.gis.postgis.geojson.introspection.Annotated;
import com.gis.postgis.geojson.introspection.IntrospectionDocumentFactory;
import com.google.common.collect.ListMultimap;

import static com.gis.postgis.geojson.GeoJson.GEOMETRIES;

/**
 * 〈功能简述〉<br>
 * 〈〉
 *
 * @author Mr.QL
 * @ClassName FeatureCollectionGeoJsonParser
 * @Date 2022-03-12 23:13
 * @Version 1.0
 */
public class GeometryCollectionGeoJsonParser<T> extends BaseIgnoreDeserializerObjectMapper<T> implements GeoJsonBaseParser<T> {
    public GeometryCollectionGeoJsonParser(JavaType valueType, Class<? extends GeoJsonDeserializer> deserializeClazz) {
        super(valueType, deserializeClazz);
    }

    @Override
    public T deserialize(JsonParser jsonParser) throws IOException {
        ObjectMapper mapper = (ObjectMapper) jsonParser.getCodec();
        //ObjectCodec oc = jsonParser.getCodec();
        ObjectNode nodeObject = (ObjectNode) mapper.readTree(jsonParser);
        // 取JSON数组
        ArrayNode geometries = nodeObject.withArray(GEOMETRIES);
        // 创建ObjectNode
        ObjectMapper copyMapper = getIgnoreDeserializerAnnotationMapper(mapper);
        ObjectNode objectNode = copyMapper.createObjectNode();
        //获取对象空间数据字段反序列化名称
        String geometriesFieldName = null;
        try {
            ListMultimap<Class<? extends Annotation>, Annotated> index = IntrospectionDocumentFactory.index(valueType.getRawClass());
            Annotated featuresAnnotated = IntrospectionDocumentFactory.oneOrNull(index, GeoJsonGeometries.class);
            geometriesFieldName = featuresAnnotated.getName();
        } catch (DocumentFactoryException e) {
            e.printStackTrace();
        }
        if (null != geometriesFieldName && null != geometries) {
            objectNode.set(geometriesFieldName, geometries);
        }
        //JsonParser parser = copyMapper.treeAsTokens(objectNode);
        //T t = copyMapper.readValue(parser, valueType);
        T t = copyMapper.convertValue(objectNode, valueType);
        return t;

    }
}
